Metaweb.View.Toolbar = function(controller) {
  this.controller = controller;
  this.ownRating = 0;
  this.averageRating = null;
  this.hasRated = false;
  this.history = new Metaweb.View.Toolbar.History(this.controller);
  this.settings = new Metaweb.View.Toolbar.Settings(this.controller);
}

Metaweb.View.Toolbar.prototype = {
  onLogin : function() {
    this.loginBox = new Metaweb.View.LoginBox(this.controller);
    window.openDialog("chrome://metaweb/content/loginWindow.xul",
                      "metawebLogin", "chrome,centerscreen", this.loginBox);
  },

  onRegister : function() {
    this.registerBox = new Metaweb.View.RegisterBox(this.controller);
    window.openDialog("chrome://metaweb/content/registerWindow.xul",
                      "metawebRegister", "chrome,centerscreen",
                      this.registerBox);
  },

  onLogout : function() {
    this.controller.model.connection.logout();
  },

  onInviteUser : function() {
    this.inviteUserBox = new Metaweb.View.InviteUserBox(this.controller);
    window.openDialog("chrome://metaweb/content/inviteUserWindow.xul",
                      "metawebInvite", "chrome,centerscreen",
                      this.inviteUserBox);
  },

  onLoginSuccess : function(username) {
    if (this.loginBox) {
      this.loginBox.onLoginSuccess();
    }
    document.getElementById("menuitem_login").setAttribute("disabled","true");
    document.getElementById("menuitem_logout").setAttribute("disabled","false");
    document.getElementById("button_signings").setAttribute("label", username);
    document.getElementById("textbox_follow_user").setAttribute(
        "hidden", "false");
    document.getElementById("button_signings").setAttribute("style",
        "list-style-image: url('chrome://metaweb/skin/circle_green.png')");
    document.getElementById("toolbaritem_userrating").setAttribute("hidden",
        "false");
    document.getElementById("toolbaritem_add_tag").setAttribute("hidden",
        "false");
    document.getElementById("button_history").setAttribute("hidden",
        "false");
	  document.getElementById("button_settings").setAttribute("hidden",
        "false");
    document.getElementById("button_invite_friend").setAttribute("hidden",
        "true");
  },

  onRegisterSuccess : function() {
    this.registerBox.onRegisterSuccess();
  },

  onLogoutSuccess : function() {
    document.getElementById("menuitem_login").setAttribute("disabled","false");
    document.getElementById("menuitem_logout").setAttribute("disabled","true");
    document.getElementById("button_signings").setAttribute("label", "Sign in");
    document.getElementById("textbox_follow_user").setAttribute(
        "hidden", "true");
    document.getElementById("button_signings").setAttribute("style",
        "list-style-image: url('chrome://metaweb/skin/circle_red.png')");
    document.getElementById("toolbaritem_userrating").setAttribute("hidden",
        "true");
    document.getElementById("toolbaritem_add_tag").setAttribute("hidden",
        "true");
    document.getElementById("button_history").setAttribute("hidden",
        "true");
    document.getElementById("button_settings").setAttribute("hidden",
        "true");
    document.getElementById("menuitem_settings_insert_ratings").setAttribute("checked",
        "false");
    document.getElementById("button_invite_friend").setAttribute("hidden",
        "true");
  },

  onFollow : function() {
    var user = document.getElementById("textbox_follow_user").value;
    this.controller.model.openedTabList.sendFollowRequest(user);
  },

  onUnfollow : function() {
    this.controller.model.openedTabList.sendUnfollowRequest();
    document.getElementById("deck_follow").setAttribute("selectedIndex", "0");
  },

  onFollowRequestReceived : function(requester, requester_nick,
                                     requester_tabid, url) {
    this.followRequestWindow = new Metaweb.View.FollowRequestWindow(
        this.controller, requester, requester_nick, requester_tabid, url);
    window.openDialog("chrome://metaweb/content/FollowRequestWindow.xul",
                      "metawebFollowRequest", "chrome,centerscreen",
                      this.followRequestWindow);
  },

  onFollowSuccess : function() {
    document.getElementById("deck_follow").setAttribute("selectedIndex", "1");
  },

  changeFollowing : function(followed) {
    if (followed) {
      document.getElementById("textbox_follow_user").value = followed;
      document.getElementById("deck_follow").setAttribute("selectedIndex", "1");
    } else {
      document.getElementById("textbox_follow_user").value = "";
      document.getElementById("deck_follow").setAttribute("selectedIndex", "0");
    }
  },

  lightUpStars : function(star_nr) {
    var current_star = null;
    for (var id = 1; id <= 5; ++id) {
      current_star = document.getElementById("star_" + id);
      if (id <= star_nr) {
        current_star.setAttribute("src", "chrome://metaweb/skin/star_20px.png");
      } else {
        current_star.setAttribute("src", "chrome://metaweb/skin/star_grey_20px.png");
      }
    }
  },
                                            
  starsOnMouseOut : function() {
    if (this.hasRated > 0) {
      this.lightUpStars(parseInt(this.ownRating));
    } else {
      this.lightUpStars(0); 
    }
  },
  
  lightUpAvgStars : function(star_nr) {
    var current_star = null;
    var basis = Math.floor(star_nr);
    var rest = star_nr - basis;
    for (var id = 1; id <= 5; id++) {
      current_star = document.getElementById("avg_star_" + id);
      if (id <= basis) {
        current_star.setAttribute("src", "chrome://metaweb/skin/star_20px.png");
      } else {
        current_star.setAttribute("src", "chrome://metaweb/skin/star_grey_20px.png");
      }
    }
    if (rest > 0) {
      current_star = document.getElementById("avg_star_" + (basis + 1));
      if (rest <= 0.125) {
        current_star.setAttribute("src", "chrome://metaweb/skin/star_grey.png");
      } else if (rest <= 0.375) {
        current_star.setAttribute("src", 
            "chrome://metaweb/skin/star_grey_25_20px.png");
      } else if (rest <= 0.625) {
        current_star.setAttribute("src", 
            "chrome://metaweb/skin/star_grey_50_20px.png"); 
      } else if (rest <= 0.875) {
        current_star.setAttribute("src",
            "chrome://metaweb/skin/star_grey_75_20px.png");      
      } else {
        current_star.setAttribute("src",
            "chrome://metaweb/skin/star.png");      
      }
    }
  },

  ratePage : function(rating) {
    this.controller.model.rating.updatePageRating(
        document.title, parseInt(rating));
  },

  onUpdatePageRatingSuccess : function(userRating, averageRating) {
    this.lightUpAvgStars(averageRating);
    this.lightUpStars(userRating);
    this.ownRating = userRating;
    this.averageRating = averageRating;
    this.hasRated = this.ownRating > 0;
  },

  onAddTag : function() {
    var tag = Metaweb.Utility.trim(
        document.getElementById("textbox_add_tag").value);
    if (tag.length > 0)
        this.controller.model.tag.addTag(tag);
  },
  
  showTagsTextbox : function(xmltags) {
    var tag_textbox = document.getElementById("textbox_add_tag");
    var param = "[";
    var all_tags = xmltags.alltag.tag;
    if (all_tags.length() > 0) {
      for ( var i = 0; i < all_tags.length(); ++i) {
        var tag = all_tags[i].text;
        var comment = all_tags[i].comment
        param += "{\"value\":\"" + tag + "\",\"comment\":\"" + comment + "\"},";
      }
    }  
    param = param.substring(0, param.length - 1); param += "]";
    tag_textbox.setAttribute("autocompletesearchparam" , param);
  },
  
  onStopGuidingSignalReceived : function() {
    window.openDialog("chrome://metaweb/content/stopGuidingWindow.xul",
                      "metawebStopGuiding", "chrome,centerscreen");
  },

  onFollowTextboxClicked : function() {
    var suggestion = "";
    var users = this.controller.model.chatRoomList
        .displayedChatRoom["chat"].roomParticipant;
    var temp = new Array();
    for (var user in users) {
      temp.push("{\"value\":\"" + users[user] + "\"}");
    }

    suggestion = "[" + temp.join(",") + "]";
    document.getElementById("textbox_follow_user").setAttribute(
        "autocompletesearchparam", suggestion);
  }

};


Metaweb.View.Toolbar.Settings = function(controller) {
  this.controller = controller;
  this.children = new Object();
};

Metaweb.View.Toolbar.Settings.prototype = {
	
    onInsertPageRatings : function() {
      var insertRatingsMenuItem = document.getElementById("menuitem_settings_insert_ratings");
      this.controller.insertPageRatings(insertRatingsMenuItem.getAttribute("checked"));
    },
    
    setInsertRatingsCheck : function(value) {
      var insertRatingsMenuItem = document.getElementById("menuitem_settings_insert_ratings");
      insertRatingsMenuItem.setAttribute("checked", value); 
    },
    
    isInsertRatingsChecked : function() {
      var insertRatingsMenuItem = document.getElementById("menuitem_settings_insert_ratings");
      if (insertRatingsMenuItem.getAttribute("checked") == "true") 
        return true;
      return false;
    },
    
};


Metaweb.View.Toolbar.History = function(controller) {
  this.controller = controller;
  this.children = new Object();
};

Metaweb.View.Toolbar.History.prototype = {
  addHistory : function(url, title) {
    if (title == "") {
      title = url;
    }
    var historyMenu = document.getElementById("menupopup_history"); 
    if (!this.children[url]) {
      this.children[url] = title;
      var newHistoryEntry = document.createElement("menuitem"); 
      newHistoryEntry.setAttribute("label", title); 
      newHistoryEntry.setAttribute("value", url); 
      newHistoryEntry.setAttribute("onclick",
        "metawebController.view.toolbar.history.goToHistoryPage(this);");
      newHistoryEntry.setAttribute("onmousedown",
        "metawebController.view.toolbar.history.onMouseDown(this, event);");
      newHistoryEntry.setAttribute("onmouseup",
        "metawebController.view.toolbar.history.onMouseUp(this, event);"); 
      historyMenu.appendChild(newHistoryEntry); 
    } 
    if (historyMenu.childNodes.length > 20) { 
      var first_url = historyMenu.firstChild.value;
      delete this.children[first_url];
      historyMenu.removeChild(historyMenu.firstChild);
    }
  },

  onMouseDown : function(target, event) { 
    this.draggedMenuItem = target; 
  }, 
  
  onMouseUp : function(target, event) { 
    if (String(this.draggedMenuItem.value) != 
        String(target.value)) { 
      this.createLinkWindow = new Metaweb.View.CreateLinkWindow(
          this.controller, this.draggedMenuItem.value, target.value);
      window.openDialog("chrome://metaweb/content/createLinkWindow.xul",
                      "metawebCreateLink", "chrome,centerscreen",
                      this.createLinkWindow);
    } 
  }, 
  
  goToHistoryPage : function(target) { 
    content.window.location.href = target.value; 
  }
};

Metaweb.View.InviteUserBox = function(controller) {
  this.controller = controller;
};

Metaweb.View.InviteUserBox.prototype = {
  initialize : function(win) {
    this.inviteUserWindow = win;
    this.emailTextbox = win.document.getElementById('textbox_email');
    this.errorLabel = win.document.getElementById('label_error');
    this.submitButton = win.document.getElementById('button_submit');
  },

  onInviteUser : function() {
    var emailPattern = new RegExp("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@"
        + "([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$");
    var emails = this.emailTextbox.value.split("\n");
    for (var i = 0; i < emails.length; ++i) {
      emails[i] = Metaweb.Utility.trim(emails[i]);
      if (!emailPattern.test(emails[i])) {
        this.errorLabel.setAttribute('value', 'Invalid email!');
        return;
      }
    }
    this.submitButton.setAttribute("disabled", "true");
    this.errorLabel.setAttribute("value", "Sending invitation ...");
    this.controller.model.connection.inviteUser(emails.join(','));    
  },

  onSuccess : function(xmlresult) {
    this.inviteUserWindow.close();
    if (xmlresult.returncode == "1") {
      alert(xmlresult.message);
    } else {
      alert(xmlresult.errormessage);
    }
  }
}

Metaweb.View.LoginBox = function(controller) {
  this.controller = controller;
};

Metaweb.View.LoginBox.prototype = {
  initialize : function(win) {
    this.loginWindow = win;
    this.errorTextbox = win.document.getElementById("login_error_msg");
    this.usernameTextbox = win.document.getElementById("textbox_username");
    this.passwordTextbox = win.document.getElementById("textbox_password");
  },

  onLogin : function() {
    if (this.usernameTextbox.value == "") {
      this.onError("User name must not be empty!");
    } else if (this.passwordTextbox.value == "") {
      this.onError("Password must not be empty!");
    } else {
      this.onError("");
      this.controller.model.connection.login(this.usernameTextbox.value,
          this.passwordTextbox.value);
    }
  },

  onError : function(error_message) {
    this.errorTextbox.value = error_message;
  },

  onLoginSuccess : function() {
    this.loginWindow.close();
  },

  onRegister : function() {
    this.loginWindow.close();
    this.controller.view.toolbar.onRegister();
  }
};

Metaweb.View.RegisterBox = function(controller) {
  this.controller = controller;
}

Metaweb.View.RegisterBox.prototype = {
  initialize : function(win) {
    this.registerWindow = win;

    this.usernameTextbox = 
        win.document.getElementById('textbox_register_username');
    this.emailTextbox =
        win.document.getElementById('textbox_register_email');
    this.passwordTextbox = 
        win.document.getElementById('textbox_register_password');
    this.confirmPasswordTextbox = 
        win.document.getElementById('textbox_confirm_password');
    this.errorMessageTextbox = 
        win.document.getElementById('register_error_msg');
    this.registerButton =
        win.document.getElementById('button_submit');
    this.registerLabel =
        win.document.getElementById('label_register');
  },

  onRegister : function() {
    var emailPattern = new RegExp("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@"
        + "([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$");
    if (this.usernameTextbox.value == "") {
      this.onError("User name must not be empty!");
    } else if (this.emailTextbox.value == "") {
      this.onError("Email must not be empty!");
    } else if (!emailPattern.test(this.emailTextbox.value)) {
      this.onError("Email not valid!");
    } else if (this.passwordTextbox.value == "") {
      this.onError("Password must not be empty!");
    } else if (this.passwordTextbox.value != 
        this.confirmPasswordTextbox.value) {
      this.onError("Password does not match!");
    } else {
      this.controller.model.connection.registerNewUser(
          this.usernameTextbox.value, this.passwordTextbox.value,
          this.emailTextbox.value);
      this.onRegisterSubmit();
    }
  },

  onError : function(error_message) {
    this.errorMessageTextbox.setAttribute("hidden", "false");
    this.registerLabel.setAttribute("hidden", "true");
    this.registerButton.setAttribute("disabled", "false");
    this.errorMessageTextbox.value = error_message;
  },

  onRegisterSubmit : function() {
    this.errorMessageTextbox.setAttribute("hidden", "true");
    this.registerLabel.setAttribute("hidden", "false");
    this.registerButton.setAttribute("disabled", "true");
  },

  onRegisterSuccess : function() {
    alert("A confirmation email will be send to you.\n"
         + "Please follow the instructions on the mail to complete your"
         + " registration!");
    this.registerWindow.close();
  }
}

Metaweb.View.FollowRequestWindow = function(controller, username, 
                                            usernick, tabid, url) {
  this.controller = controller;
  this.requester = username;
  this.requesterTabid = tabid;
  this.usernick = usernick;
  this.url = url;
}

Metaweb.View.FollowRequestWindow.prototype = {
  initialize : function(win) {
    this.followRequestWindow = win;

    this.followRequestMessage1 =
        win.document.getElementById('follow_request_msg1');
    this.followRequestMessage2 =
        win.document.getElementById('follow_request_msg2');
    this.followRequestMessage1.value = "User " + this.requester + 
        " has requested to follow you";
    this.followRequestMessage2.value = 
        "on the tab currently showing URL: " + this.url;
  },

  onResponse : function(response) {
    this.controller.model.openedTabList.sendFollowResponse(response,
        this.requester, this.usernick, this.requesterTabid, this.url);
    this.followRequestWindow.close();
  }
}

Metaweb.View.CreateLinkWindow = function(controller, from, to) {
  this.controller = controller;
  this.from = from;
  this.to = to;
}

Metaweb.View.CreateLinkWindow.prototype = {
  initialize : function(win) {
    this.createLinkWindow = win;
    this.fromTextbox = win.document.getElementById('textbox_from_link');
    this.toTextbox = win.document.getElementById('textbox_to_link');
    this.noteTextbox = win.document.getElementById('textbox_link_note');

    this.fromTextbox.value = this.from;
    this.toTextbox.value = this.to;
  },

  onOk : function() {
    this.controller.model.link.addLink(this.fromTextbox.value, 
                                       this.toTextbox.value,
                                       this.noteTextbox.value);
    this.createLinkWindow.close();
  },

  onCancel : function() {
    this.createLinkWindow.close();
  }

}

window.addEventListener("load", function() {
  window.metawebController = new Metaweb.Controller();
  metawebController.initialize();
  metawebController.view.toolbar = new Metaweb.View.Toolbar(metawebController);
  window.addEventListener("unload", function() {
    metawebController.stop();
  }, false);
}, false);


